'use client'

import { createClient } from '@/lib/supabase/client'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts'
import { ArrowUpRight, Calendar, Target, Plus, Edit, Trash2 } from 'lucide-react'
import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent } from '@/components/ui/dialog'
import { useToast } from '@/components/ui/use-toast'
import { ToastProvider } from '@/components/ui/use-toast'
import GoalForm from '@/components/dashboard/goal-form'

export default function ProgressPage() {
  // 注意：在实际应用中，ToastProvider通常应该在更高级别的组件中提供
  // 这里只是为了快速修复错误而临时添加
  return (
    <ToastProvider>
      <ProgressPageContent />
    </ToastProvider>
  )
}

function ProgressPageContent() {
  const toast = useToast()
  const [user, setUser] = useState<{ id: string; email: string; [key: string]: any } | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [goals, setGoals] = useState<Array<{ id?: number, title?: string, current?: number, target?: number, status?: 'in_progress' | 'completed' }>>([])
  const [selectedGoal, setSelectedGoal] = useState<{ id?: number, title?: string, current?: number, target?: number, status?: 'in_progress' | 'completed' } | null>(null)
  const [openDialog, setOpenDialog] = useState(false)

  useEffect(() => {
    async function fetchUser() {
      try {
        const supabase = createClient()
        const { data: { user } } = await supabase.auth.getUser()
        
        if (!user) {
          window.location.href = '/auth/signin'
          return
        }
        
        setUser(user)
        setLoading(false)
      } catch (err) {
        setError('Failed to fetch user')
        setLoading(false)
        console.error(err)
      }
    }
    
    fetchUser()
  }, [])

  // Fetch progress data (this would typically come from Supabase)
  const progressData = [
    { week: 'Week 1', mood: 3, anxiety: 6, progress: 10 },
    { week: 'Week 2', mood: 4, anxiety: 5, progress: 25 },
    { week: 'Week 3', mood: 5, anxiety: 4, progress: 40 },
    { week: 'Week 4', mood: 4, anxiety: 5, progress: 50 },
    { week: 'Week 5', mood: 6, anxiety: 3, progress: 65 },
    { week: 'Week 6', mood: 7, anxiety: 2, progress: 80 },
  ]

  // Fetch goals from Supabase
  useEffect(() => {
    async function fetchGoals() {
      if (!user) return

      try {
        const supabase = createClient()
        const { data, error } = await supabase
          .from('goals')
          .select('*')
          .eq('user_id', user?.id)
          .order('created_at', { ascending: false })

        if (error) throw error
        setGoals(data || [])
      } catch (err) {
        setError('Failed to fetch goals')
        console.error('Error fetching goals:', err)
      }
    }

    fetchGoals()
  }, [user])

  // Handle creating/updating goals
  const handleGoalSubmit = () => {
    // Refresh goals list after submit
    const supabase = createClient()
    supabase
      .from('goals')
      .select('*')
      .eq('user_id', user?.id)
      .order('created_at', { ascending: false })
      .then(({ data, error }: { data: typeof goals | null; error: any }) => {
        if (!error) {
          setGoals(data || [])
        }
      })
  }

  // Handle deleting goal
  const handleDeleteGoal = async (goalId: number | undefined) => {
    if (!goalId) return;
    if (!confirm('Are you sure you want to delete this goal?')) return

    try {
      const supabase = createClient()
      const { error } = await supabase
        .from('goals')
        .delete()
        .eq('id', goalId)
        .eq('user_id', user?.id)

      if (error) throw error
      toast({ title: 'Goal deleted successfully' })
      // Update goals list
      setGoals(goals.filter(goal => goal?.id !== goalId))
    } catch (err) {
      setError('Failed to delete goal')
      console.error('Error deleting goal:', err)
    }
  }

  if (loading) {
    return <div>Loading...</div>
  }

  if (error) {
    return <div className="text-red-500">{error}</div>
  }

  return (
    <div className="min-h-screen" style={{ backgroundColor: '#FAF9F5' }}>
      <div className="max-w-6xl mx-auto p-8">
        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-black mb-4">Your Therapeutic Progress</h1>
          <p className="text-xl text-gray-700">Track your journey and celebrate your growth</p>
        </div>

        {/* Progress Overview */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
          <Card style={{ backgroundColor: '#BCD1CA' }}>
            <CardHeader>
              <CardTitle>Mood Improvement</CardTitle>
              <CardDescription>Current mood score: 7/10</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex justify-between items-center">
                <div className="text-3xl font-bold">+4</div>
                <div className="flex items-center text-green-700">
                  <ArrowUpRight size={20} />
                  <span className="ml-1 font-medium">40%</span>
                </div>
              </div>
              <p className="text-sm text-gray-600 mt-2">vs. starting point</p>
            </CardContent>
          </Card>

          <Card style={{ backgroundColor: '#E8E3D3' }}>
            <CardHeader>
              <CardTitle>Anxiety Reduction</CardTitle>
              <CardDescription>Current anxiety: 2/10</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex justify-between items-center">
                <div className="text-3xl font-bold">-4</div>
                <div className="flex items-center text-green-700">
                  <ArrowUpRight size={20} className="transform rotate-180" />
                  <span className="ml-1 font-medium">67%</span>
                </div>
              </div>
              <p className="text-sm text-gray-600 mt-2">vs. starting point</p>
            </CardContent>
          </Card>

          <Card style={{ backgroundColor: '#C8C6C6' }}>
            <CardHeader>
              <CardTitle>Session Completion</CardTitle>
              <CardDescription>Total sessions: 12</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex justify-between items-center">
                <div className="text-3xl font-bold">80%</div>
                <div className="flex items-center">
                  <Calendar size={20} />
                  <span className="ml-1 font-medium">6/8 weeks</span>
                </div>
              </div>
              <p className="text-sm text-gray-600 mt-2">of recommended program</p>
            </CardContent>
          </Card>
        </div>

        {/* Progress Chart */}
        <Card className="mb-8">
          <CardHeader>
            <CardTitle>Progress Over Time</CardTitle>
            <CardDescription>Track your mood, anxiety, and overall progress</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="h-80">
              <ResponsiveContainer width="100%" height="100%">
                <LineChart data={progressData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                  <XAxis dataKey="week" />
                  <YAxis />
                  <Tooltip />
                  <Line type="monotone" dataKey="mood" stroke="#4CAF50" strokeWidth={2} activeDot={{ r: 8 }} />
                  <Line type="monotone" dataKey="anxiety" stroke="#F44336" strokeWidth={2} />
                  <Line type="monotone" dataKey="progress" stroke="#2196F3" strokeWidth={2} />
                </LineChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>

        {/* Goals Section */}
        <Card>
          <CardHeader className="flex justify-between items-center">
            <div>
              <CardTitle>Your Goals</CardTitle>
              <CardDescription>Track your therapeutic objectives</CardDescription>
            </div>
            <Button
                  variant="default"
                  size="sm"
                  onClick={() => {
                    setSelectedGoal(null)
                    setOpenDialog(true)
                  }}
                >
              <Plus size={16} className="mr-1" />
              New Goal
            </Button>
          </CardHeader>
          <CardContent>
            {goals.length === 0 ? (
              <div className="text-center py-8">
                <p className="text-gray-500 mb-4">No goals yet. Create your first goal to start tracking your progress!</p>
                <Button
                  variant="default"
                  size="sm"
                  onClick={() => {
                    setSelectedGoal(null)
                    setOpenDialog(true)
                  }}
                >
                  <Plus size={16} className="mr-1" />
                  Create First Goal
                </Button>
              </div>
            ) : (
              <div className="space-y-6">
                {goals.map((goal) => (
                  <div key={goal?.id} className="space-y-2 p-4 border border-gray-100 rounded-lg hover:bg-gray-50 transition-colors">
                    <div className="flex justify-between items-center">
                      <div className="flex items-center">
                        <Target size={18} className={`mr-2 ${goal.status === 'completed' ? 'text-green-500' : 'text-blue-500'}`} />
                        <span className="font-medium">{goal.title}</span>
                      </div>
                      <div className="flex items-center space-x-2">
                        <span className={`text-sm font-medium px-2 py-1 rounded-full ${goal.status === 'completed' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}`}>
                          {goal.status === 'completed' ? 'Completed' : 'In Progress'}
                        </span>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => {
                            setSelectedGoal(goal)
                            setOpenDialog(true)
                          }}
                        >
                          <Edit size={16} className="text-gray-500" />
                        </Button>
                        <Button
                          variant="destructive"
                          size="icon"
                          onClick={() => handleDeleteGoal(goal?.id)}
                          aria-label="Delete goal"
                        >
                          <Trash2 size={16} />
                        </Button>
                      </div>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2.5">
                      <div
                        className={`h-2.5 rounded-full ${goal.status === 'completed' ? 'bg-green-500' : 'bg-blue-500'}`}
                        style={{ width: `${goal.current}%` }}
                      ></div>
                    </div>
                    <div className="flex justify-between text-sm text-gray-500">
                      <span>{goal.current}%</span>
                      <span>Target: {goal.target}%</span>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Goal Form Dialog */}
        <Dialog open={openDialog} onOpenChange={setOpenDialog}>
          <DialogContent className="p-0 overflow-hidden">
            <GoalForm
              initialData={selectedGoal || undefined}
              onClose={() => setOpenDialog(false)}
              onSubmit={handleGoalSubmit}
            />
          </DialogContent>
        </Dialog>
      </div>
    </div>
  )
}